package com.zc.dao;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLDecoder;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import java.util.Properties;

import javax.sql.DataSource;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.zc.entity.User;

public class DBPool {
	private DataSource dataSource = null;
	
	private DBPool() {
		try {
			//初始化数据源
			dataSource = DruidDataSourceFactory.createDataSource(getProperties("db.properties"));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	private static DBPool pool = null;
	
	//获取实例
	public static DBPool getInstance() {
		if (pool == null) {
			pool = new DBPool();
		}
		return pool;
	}
	
	//通过数据源获取连接
	public Connection getConnection() throws SQLException {
		return dataSource.getConnection();
	}
	
	//获取数据源
	public DataSource getDataSource() {
		return dataSource;
	}

	/**
	 * 	通过这个类的反射获取项目的根目录，最终得到一个Properties对象
	 * @param prosPath Properties文件的路径
	 * @return 加载了Properties文件的对象
	 * @throws Exception 
	 */
	public Properties getProperties(String prosPath) throws Exception {
		//1.创建一个properties对象
		//这个对象里面就有操作这个properties文件所有方法
		Properties pros = new Properties();
		//2.获取源文件的字节输入流
		InputStream inStream = null;
		try {
			//class文件所在的位置的根目录。
			String path = DBPool.class.getResource("/").getPath();
			//将中文的url编码解析%ert%weq
			path = URLDecoder.decode(path, "utf-8");
			inStream = new FileInputStream(path + "\\" + prosPath);
			//3.properties对象加载源文件
			pros.load(inStream);
		} catch (FileNotFoundException e) {
			throw new FileNotFoundException("Properties文件路径未找到!");
		} catch (IOException e) {
			throw new IOException("Properties文件流加载失败!");
		}
		return pros;
	}
	
	
	public static void main(String[] args) {
		DBPool dbPool= DBPool.getInstance();
		try {
			QueryRunner runner = new QueryRunner(dbPool.getDataSource());
			String sql = "select * from lpm_user";
			List<User> users = runner.query(sql, new BeanListHandler<User>(User.class));
			System.out.println(users);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
